<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\PaneltplRequest;
use App\Models\Application\Paneltpl;
use App\Repositories\Application\PaneltplRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;
use DB;

class PaneltplController extends Controller
{
    use ModelForm;

    /** @var  PaneltplRepository */
    private $paneltplRepository;

    public function __construct(PaneltplRepository $paneltplRepo)
    {
        $this->paneltplRepository = $paneltplRepo;
    }

    /**
     * Display a listing of the Paneltpl.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.paneltpls.index_header'));
            $content->description(__('application.paneltpls.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Paneltpl.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.paneltpls.create_header'));
            $content->description(__('application.paneltpls.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Paneltpl in storage.
     *
     * @param PaneltplRequest $request
     *
     * @return Response
     */
    public function store(PaneltplRequest $request)
    {
        $input = $request->all();
        $image = $request->file('ui'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.paneltpl');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['ui'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $paneltpl = $this->paneltplRepository->create($input);

        Flash::success(__('application.paneltpls.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.paneltpls.index'));

    }

    /**
     * Display the specified Paneltpl.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $paneltpl = $this->paneltplRepository->findWithoutFail($id);

        if (empty($paneltpl)) {
            Flash::error(__('application.paneltpls.not_found'));

            return redirect(route('application.paneltpls.index'));
        }

        return view('application.paneltpls.show')->with('paneltpl', $paneltpl);

    }

    /**
     * Show the form for editing the specified Paneltpl.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.paneltpls.edit_header'));
            $content->description(__('application.paneltpls.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Paneltpl in storage.
     *
     * @param  int              $id
     * @param PaneltplRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $paneltpl = $this->paneltplRepository->findWithoutFail($id);

        if (empty($paneltpl)) {
            Flash::error(__('application.paneltpls.not_found'));

            return redirect(route('application.paneltpls.index'));
        }
        $input = $request->all();

        // 如果删除原图
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl       = $paneltpl->ui;
            $uploadConfig = config('custom.base.upload.paneltpl');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $rootDir      = config('filesystems.disks.' . $driver . '.upload');
            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $paneltpl->ui = null;
                $paneltpl->save();
            };
            return response()->json(['message' => '删除成功', 'status' => true]);
        }

        $sValidators = [
            'name'  => 'required|max:100',
            'areas' => 'required',

        ];

        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), $validators, [
            'required' => ':attribute 不能为空',
        ], [
            'name'  => '名称',
            'areas' => '区位信息',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }

        $image = $request->file('ui'); //使用laravel 自带的request类来获取一下文件
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.paneltpl');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['ui'] = $fullPath;
                $flag        = Storage::disk($driver)->delete($paneltpl->img);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $paneltpl = $this->paneltplRepository->update($input, $id);

        Flash::success(__('application.paneltpls.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.paneltpls.index'));
    }

    /**
     * Remove the specified Paneltpl from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->paneltplRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.paneltpls.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $paneltpl = $this->paneltplRepository->findWithoutFail($id);

        if (empty($paneltpl)) {
            Flash::error(__('application.paneltpls.not_found'));

            return redirect(route('application.paneltpls.index'));
        }

        if ($flag = $this->paneltplRepository->delete($id)) {

            return response()->json(['message' => __('application.paneltpls.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Paneltpl::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', 'panel模板名称');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->textarea('areas', '区位信息');
            // $paneltplTypes = PaneltplType::pluck('name', 'id');
            // $form->select('paneltpl_type_id', 'paneltpl模板类型')->options($paneltplTypes);
            $form->image('ui', 'ui')->removable();
            $form->textarea('description', '描述');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Paneltpl::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.paneltpls.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.paneltpls.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.paneltpls.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.paneltpls.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.paneltpls.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.paneltpls.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id = $actions->getKey();
                // 编辑按钮
                if (Admin::user()->cannot('application.paneltpls.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.paneltpls.destroy')) {
                    $actions->disableDelete();
                }
                // 跳转到模板区位信息定义
                $actions->append('<a href=' . route('application.paneltpl_areas.index', ['paneltpl_id' => $id]) . ' onclick="" title="区位编辑">&nbsp;&nbsp;区位编辑/</a>');
                $actions->append('<a href=' . route('entity.asset.video.vassetis.compress_upload_view', ['paneltpl_id' => $id]) . ' onclick="" title="上传模板">&nbsp;&nbsp;上传模板/</a>');
            });

            // 导出按钮
            if (Admin::user()->cannot('application.paneltpls.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.paneltpls.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', 'panel模板名称')->sortable();
            $grid->column('areas', '区位信息')->sortable();
            // $grid->column('paneltplType.name', '模板类型')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $uploadConfig = config('custom.base.upload.paneltpl');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('ui', 'ui')->image($host)->display(function ($val) {
                $table_name  = $this->getTable();
                $table_field = 'ui';
                $id          = $this->id;
                return '<a href=' . route('application.apppages.images.index', ['model' => $table_name, 'column' => $table_field, 'id' => $id]) . '>' . $val . '</a>';
            });
            $grid->column('description', '描述')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }

    /**
     * 压缩文件上传视图
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function compressUploadView(Request $request)
    {
        $paneltplId = $request->input('paneltpl_id');
        $paneltpl   = $this->paneltplRepository->findWithoutFail($paneltplId);
        if (empty($paneltpl)) {
            Flash::error(__('application.paneltpls.not_found'));

            return redirect(route('application.paneltpls.index'));
        }
        // 获取相关模板文件
        return Admin::content(function (Content $content) use ($paneltpl) {
            $content->header(__('模板文件上传'));
            $content->description(__('模板文件上传'));
            $instruction = '<p><b>模板名称:</b>' . $paneltpl->name . '</p>';
            $instruction .= '<p><b>模板标题:</b>' . $paneltpl->title . '</p>';
            $instruction .= '<p>点击 "下载压缩文件" 按钮, 按照目录结构存放文件!<b>(html目录下文件名格式为: 模板名称.blade.php)</b><a href="/upload/compress_upload/upload_example.zip" class="btn btn-warning" target="_blank"><i class="fa fa-download"></i>下载压缩文件</a></p>';
            $box = new Box('当前模板详情', $instruction);
            $content->row($box->style('primary'));

            $content->body($this->compressUploadForm($paneltpl));
        });
    }

    /**
     * 批量的导入媒资的form
     */
    protected function compressUploadForm($paneltpl)
    {
        // 文件
        return Admin::form(Paneltpl::class, function (Form $form) use ($paneltpl) {
            // 设置表单提交的action
            $form->setAction(route('entity.asset.video.vassetis.compress_upload'));
            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                // $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                // $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
            });
            Admin::script('uploadTemplate();');
            $form->hidden('paneltpl_id', 'paneltpl模板')->value($paneltpl->id);

            $form->file('file', 'zip文件')->help('压缩文件后缀为.zip');
        });
    }

    /**
     * 保存上传模板数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function compressUpload(Request $request)
    {
        $input      = $request->all();
        $paneltplId = $request->input('paneltpl_id');
        $paneltpl   = $this->paneltplRepository->findWithoutFail($paneltplId);
        if (empty($paneltpl)) {
            return response()->json(['status' => 'error', 'content' => '无此paneltpl模板']);
        }
        // 上传文件:
        $file = $request->file('file');
        // 获取客户端文件真实姓名
        if (!$file->isValid()) {
            return response()->json(['status' => 'error', 'content' => '文件上传失败!']);
        }
        // 文件是否上传成功
        // 允许上传的文件格式
        $allowed_extensions = ["zip"];
        // 上传文件的后缀, 扩展名
        $entension = $file->getClientOriginalExtension();
        if ($entension && !in_array($entension, $allowed_extensions)) {
            // json返回
            return response()->json(['status' => 'error', 'content' => '文件格式只能为zip!']);
        }
        $realPath = $file->getRealPath();
        // 获取上传文件的名称
        $originalName = $file->getClientOriginalName();
        //获取文件尺寸
        $size          = $file->getSize();
        $input['size'] = $size;
        // 文件最大限制, 现在是10M
        $file_max_size = config('custom.base.file_max_size');
        // 上传文件
        $fileName = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $entension;
        if ($size > $file_max_size) {
            // json返回
            return response()->json(['status' => 'error', 'content' => '文件最大只能10M!']);
        }
        // 上传文件
        $bool = Storage::disk('template')->put($fileName, file_get_contents($realPath));
        if (empty($bool)) {
            return response()->json(['status' => 'error', 'content' => '文件上传失败!']);
        }
        // 文件上传的根路径
        $rootDir = config('filesystems.disks.template.root');
        /**
         * 文件上传成功之后对`.zip`文件进行操作
         */
        $zipper = new \Chumper\Zipper\Zipper; //新建一个ZipArchive的对象
        // 移动js,css及图片html,到相关的文件夹
        $moveJsPath     = config('custom.base.template_style.js.path');
        $moveCssPath    = config('custom.base.template_style.css.path');
        $moveImagesPath = config('custom.base.template_style.images.path');
        $moveViewPath   = config('custom.base.template_style.view.path');
        // zipper 负责将zip包中的文件解压到各个目录中去
        // dd($rootDir.$fileName);
        $zipper->make($rootDir . $fileName)->folder('js')->extractTo($moveJsPath);
        $zipper->make($rootDir . $fileName)->folder('css')->extractTo($moveCssPath);
        $zipper->make($rootDir . $fileName)->folder('images')->extractTo($moveImagesPath);
        $zipper->make($rootDir . $fileName)->folder('html')->extractTo($moveViewPath);

        DB::beginTransaction();
        try {
            $history                = [];
            $history['upload_no']   = date('YmdHis');
            $history['paneltpl_id'] = $paneltplId;
            $history['url']         = '/upload/compress_upload/' . $fileName;
            $history['size']        = $size;
            $history['user_id']        = Admin::user()->id;
            $history['created_at']  = date('Y-m-d H:i:s');
            DB::table('upload_template_histories')->insert($history);
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
        }

        // 模板风格首页路由
        $url = route('application.paneltpls.index');

        return response()->json(['content' => '模板文件上传成功', 'status' => 'success', 'url' => $url]);
    }
}
